<?php
/*
 * 订单
 */

namespace app\adminbackstage\controller;
use app\adminbackstage\model\User;
use app\BaseController;
use app\common\service\CommonWxMessageService;
use app\common\service\CommonOrderService;
use think\facade\Request;
use app\adminbackstage\model\Order;


use app\api\service\OrderService;
use app\common\model\Parameter;
use app\common\model\Product;
//use app\common\model\User;
//use app\adminbackstage\model\Product;

//use app\adminbackstage\model\InventoryTotal;

use PhpOffice\PhpSpreadsheet\Cell\DataType as PHPExcel_Cell_DataType;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment as PHPExcel_Style_Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border as Border;
use PhpOffice\PhpSpreadsheet\Style\Fill as PHPExcel_Style_Fill;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\facade\Db;

class OrderController extends BaseController{

    //订单列表
    public function orderList(){
        $a_uid = Request::param('a_uid');
        $page = Request::param('page');
        $num = Request::param('num');

        $s_name = Request::param('s_name');
        $p_name = Request::param('p_name');
        $o_pro_num = Request::param('o_pro_num');
        $p_num = Request::param('p_num');
        $type= Request::param('type');
        $state = Request::param('state');
        $phone = Request::param('phone');
        $paytime_min = Request::param('paytime_min');
        $paytime_max = Request::param('paytime_max');
        $startTime = Request::param('startTime');
        $endTime = Request::param('endTime');
        $superor_phone = Request::param('superor_phone');
        $where = [];
        $where[] = ['o.enable','=','1'];
        if(!empty($s_name)){
            $where[] = ['o.s_name','=',$s_name];
        }
        if(!empty($phone)){
            $where[] = ['u.phone','=',$phone];
        }
        if(!empty($superor_phone)){
            $where[] = ['u.superor_phone','=',$superor_phone];
        }
        if(!empty($p_name)){
//            $where[] = ['o.p_name','=',$p_name];
            $where[] = ['o.p_name','like',"%$p_name%"];
        }
        if(!empty($o_pro_num)){
            $where[] = ['o.o_pro_num','=',$o_pro_num];
        }
        
        if(!empty($p_num)){
            $where[] = ['o.p_num','=',$p_num];
        }
        if(!empty($type)){
            $where[] = ['o.type','=',$type];
        }
        if(!empty($startTime)){
            $where[] = ['o.addtime','>=',strtotime($startTime)];
        }
        if(!empty($endTime)){
            $where[] = ['o.addtime','<=',strtotime($endTime) + 86399];
        }
        if(!empty($paytime_min)){
            $where[] = ['o.paytime','>=',strtotime($paytime_min)];
        }
        if(!empty($paytime_max)){
            $where[] = ['o.paytime','<=',strtotime($paytime_max) + 86399];
        }

        if(is_numeric($state)){
            $where[] = ['o.state','=',$state];
        }
        $list = Order::orderList($where,$page,$num);
        if(!empty($list)){
            $list = $list->toArray();
            foreach ($list as $key => $value) {
                $list[$key]["addtime"] = date( "Y-m-d H:i:s",$value["addtime"]);
                if(isset($value["paytime"])){
                    $list[$key]["paytime"] = date( "Y-m-d H:i:s",$value["paytime"]);
                }
                if(isset($value["sendtime"])){
                    $list[$key]["sendtime"] = date( "Y-m-d H:i:s",$value["sendtime"]);
                }
                if(isset($value["endtime"])){
                    $list[$key]["endtime"] = date( "Y-m-d H:i:s",$value["endtime"]);
                }
                    /*if(strpos($value['img'],"img.alicdn.com") !== false){
                        $storeList[$key]["img"] =  $value['img'];
                    }
                    elseif(strpos($value['img'],"http") !== false){
                        $storeList[$key]["img"] =  $value['img'];
                    }
                    else{
                        
                        $storeList[$key]["img"] =  Config::get('app.swimming_url').$value['img'];
                    }*/
            }
        }
        $count = Order::orderCount($where);
        return json(['code' => 1, 'msg' => lang(''), 'data' => $list, 'count' => $count]);
    }
    
    //订单添加
    /*public function warehouseAdd(){
        $store = new Store();
        $a_uid = Request::param('a_uid');
        $enable = Request::param('enable');
        $w_name = Request::param('w_name');
        $type = Request::param('type');
        $province = Request::param('province');
        $city = Request::param('city');
        $district = Request::param('district');
        $address = Request::param('address');
        
        if(empty($enable)){
            $enable = 1;
        }
        if($enable == -1){
            $enable  = 0;
        }
        $time = time();
        $data = [

            'w_name' => $w_name,
            'enable' => $enable,
            'addtime' => $time,
            'type' => $type,
            'province' => $province,
            'city' => $city,
            'address' => $address,
            'district' => $district,
            'address' => $address,

        ];

        Warehouse::warehouseAdd($data);
        return json(['code' => 1, 'msg' => lang(''), 'data' => '', 'count' => '']);
    }*/
    
    //订单详情
    public function orderInfo(){
        $a_uid = Request::param('a_uid');

        $id = Request::param('id');
  
        $where = [];
        $where[] = ['id','=',$id];

        $info = Order::orderInfo($where);
        if(!empty($info)){
            $info = $info->toArray();
            $db = new User();
            $where_u = [];
            $where_u[] = ['uid','=',$info["uid"]];
            $user = $db->info($where_u);
            if(!empty($user)){
                $user = $user->toArray();
                $info["superor"] = $user['superor'];
                $info["superor_phone"] = $user['superor_phone'];
            }

            $info["addtime"] = date( "Y-m-d H:i:s",$info["addtime"]);
            
            if(isset($info["paytime"])){
                $info["paytime"] = date( "Y-m-d H:i:s",$info["paytime"]);
            }
            if(isset($info["sendtime"])){
                $info["sendtime"] = date( "Y-m-d H:i:s",$info["sendtime"]);
            }
            if(isset($info["endtime"])){
                $info["endtime"] = date( "Y-m-d H:i:s",$info["endtime"]);
            }
            /*if(strpos($storeList['img'],"img.alicdn.com") !== false){
                $storeList["img"] =  $storeList['img'];
            }
            elseif(strpos($storeList['img'],"http") !== false){
                $storeList["img"] =  $storeList['img'];
            }
            else{

                $storeList["img"] =  Config::get('app.swimming_url').$storeList['img'];
            }*/
       
        }

        return json(['code' => 1, 'msg' => lang(''), 'data' => $info, 'count' => '' ]);
    }
    
    //上一次分配
    public function lastAllocation(){
        $a_uid = Request::param('a_uid');
        $id = Request::param('id');
        $uid = Request::param('uid');
        
        $where = [];
        $where[] = ['o.uid','=',$uid];
        $where[] = ['o.enable','=',1];
        $where[] = ['o.state','>',1];
        $where[] = ['o.type','=',1];
        
        $page = 1;
        $num = 1;
        $list = Order::orderList($where,$page,$num);
        $info['stid'] = 0;
        $info['s_name'] = '';
        if(!empty($info)){
            foreach ($list as $key => $value) {
                if(!empty($value['stid'])){
                    $info['stid'] = $value['stid'];
                    $info['s_name'] = $value['s_name'];
                }
            }

        }
        return json(['code' => 1, 'msg' => lang(''), 'data' => $info, 'count' => '' ]);

        
        
    }
    
    //发货
    public function sendOutGoods(){
        $a_uid = Request::param('a_uid');
        $id = Request::param('id');
        $w_id = Request::param('wid');
        $state = Request::param('state');//0未付款 1待发货 2发货中 3收货 -1已取消
        $post_num = Request::param('post_num');//物流单号
        $stid = Request::param('stid');//门店ID 
        $s_name = Request::param('s_name');//门店名 
        $type = Request::param('type');//订单类型 
        $p_id = Request::param('p_id');//商品ID 
        $order_quantity = Request::param('order_quantity');//下单数
        $uid = Request::param('uid');
        
        $update = [];

        $orderInfo = Order::orderInfo(["id"=>$id]);
        Db::startTrans();//开启事务
        if($state==2){
            if(empty($post_num)){
                //return json(['code' => 0, 'msg' => lang('请填写物流单号'), 'data' => '', 'count' => '' ]);
            }
            
            $update['post_num']= $post_num;
            $update['sendtime']= time();
        }
        
        //OrderService
        if($type==1 && $state==2){
            if(!empty($stid)){
                $update['stid']= $stid;
            }
            if(!empty($s_name)){
                $update['s_name']= $s_name;
            }
            $p_info = Product::dataInfo(["id"=>$p_id]);
            
            /*if($order_quantity>$p_info["inventory"]){
                return json(['code' => 0, 'msg' => lang('库存不足!'), 'data' => '', 'count' => '' ]);
            }*/
            
            
            if($p_info["commission_price"] > 0){
                $userInfo = \app\common\model\User::userInfo(["uid"=>$uid]);
                $store_user = \app\common\model\User::userInfo(["stid"=>$stid]);
                
                if(!empty($userInfo["post_sta_id"])){
                    $sta_info = \app\common\model\User::userInfo(['uid'=>$userInfo["post_sta_id"]]);
                }
                else{
                    $sta_info = [];
                }
                if(!empty($userInfo["superor_id"])){
                    $sup_info = \app\common\model\User::userInfo(['uid'=>$userInfo["superor_id"]]);
                }else{
                    $sup_info = [];
                }
                $nh_store_delivery_fee = Parameter::parameterValue(["id"=>4]);
//                if($type==2){
//                    $store_user = \app\common\model\User::userInfo(["stid"=>$stid]);
//                }else{
//                    $store_user = [];
//                }
                //$store_user = \app\common\model\User::userInfo(["stid"=>$stid]);
                $commission_info = OrderService::commissionInfoCreate($p_info,$sta_info,$sup_info,$order_quantity,$nh_store_delivery_fee,$store_user);
            }else{
                $commission_info = [];
            }
            $update['commission_info']= $commission_info;

        }
        

        
        $update['state']= $state;
        
        
        /*if($state>0 && $state !=2){
            $update['state']= $state;
        }
        elseif($state==2){
            $update['state']= $state;
            $where = [];
            $where[] = ['id','=',$id];

            $info = Order::orderInfo($where);
            if($info['tinyint']==2){
                return json(['code' => 0, 'msg' => lang('该订单缺货'), 'data' => '', 'count' => '' ]);
            }
            $where_i = [];
            $where_i[] = ['w_id','=',$w_id];
            $where_i[] = ['p_id','=',$info['p_id']];
            $where_i[] = ['enable','=',1];
            
            $inventoryTotalInfo = InventoryTotal::inventoryTotalInfo($where_i);//总库存
            
            if(!empty($inventoryTotalInfo)){
                if(($inventoryTotalInfo['ware_quantity']-$inventoryTotalInfo['sold'])>=$info['order_quantity']){//库存足够

                    Db::startTrans();
                    try {
                        $time = time();
                        $update['sup_quantity']= $info['order_quantity'];
                        Order::orderEdit($id,$update);
                        
                        $sql = 'update wa_product set sold=sold+'.$info['order_quantity'].' where id='.$info['p_id'] ;
                        Product::ruleSql($sql);
                        
                        $sql_t = 'update wa_inventory_total set sold=sold+'.$info['order_quantity'].' where id='.$inventoryTotalInfo['id'] ;
                        Product::ruleSql($sql_t);


                        Db::commit();
                    }catch (\Exception $e){
                        Db::rollback();
                    }
                }
                else{
                    
                    
                    
                    return json(['code' => 0, 'msg' => lang('库存不足,请先添加'), 'data' => '', 'count' => '' ]);
                }
            }
            else{
                return json(['code' => 0, 'msg' => lang('无库存,请先添加'), 'data' => '', 'count' => '' ]);
            }
         

            
        }elseif($state<0){
            $update['state']= $state;
        }*/
        $info = Order::orderEdit($id,$update);
        if($info&&$state==2){

            $db = new User();
            $where[] = ["uid","=",$orderInfo["uid"]];
            $find = $db->info($where);
            //CommonWxMessageService::orderSendMsgSend($find["open_id"],$orderInfo["o_pro_num"],$post_num,$orderInfo["p_name"]);
            if(!empty($post_num)){
                $orderInfo["tracking_no"] = $post_num;
                $orderInfo["openid"] = $find["open_id"];
                CommonOrderService::orderDeliveryInfoSync($orderInfo);//订单微信交互
            }
        }
        
        Db::commit();//事务提交
        return json(['code' => 1, 'msg' => lang(''), 'data' => '', 'count' => '' ]);
    }
    
    //订单修改
    public function orderEdit(){

        /*$a_uid = Request::param('a_uid');
        $id = Request::param('id');
        $enable = Request::param('enable');
        $w_name = Request::param('w_name');
        $type = Request::param('type');
        $province = Request::param('province');
        $city = Request::param('city');
        $district = Request::param('district');
        $address = Request::param('address');
        
        $update = [];
        if(!empty($w_name)){
            $update['w_name'] = $w_name;
        }
        
        if(!empty($type)){
            $update['type'] = $type;
        }
        
        if(!empty($province)){
            $update['province'] = $province;
        }
        
        if(!empty($city)){
            $update['city'] = $city;
        }
        
        if(!empty($district)){
            $update['district'] = $district;
        }
        
        if(!empty($address)){
            $update['address'] = $address;
        }
        
        if($enable==-1){
            $update['enable'] = 0;
        }else{
            $update['enable'] = 1;
        }


        Warehouse::warehouseEdit($id,$update);
        return json(['code' => 1, 'msg' => lang(''), 'data' => '', 'count' => '']);*/
    }
    
    
    
    //订单导出
    public function orderDown(){
        $a_uid = Request::param('a_uid');
        $page = Request::param('page');
        $num = Request::param('num');
        
        $s_name = Request::param('s_name');
        $p_name = Request::param('p_name');
        $o_pro_num = Request::param('o_pro_num');
        $p_num = Request::param('p_num');
        $type= Request::param('type');
        $state = Request::param('state');
        $phone = Request::param('phone');
        $startTime = Request::param('startTime');
        $endTime = Request::param('endTime');
        $paytime_min = Request::param('paytime_min');
        $paytime_max = Request::param('paytime_max');
        $where = [];
        $where[] = ['o.enable','=','1'];
        if(!empty($s_name)){
            $where[] = ['o.s_name','=',$s_name];
        }
        if(!empty($phone)){
            $where[] = ['u.phone','=',$phone];
        }
        if(!empty($p_name)){
            $where[] = ['o.p_name','=',$p_name];
        }
        if(!empty($o_pro_num)){
            $where[] = ['o.o_pro_num','=',$o_pro_num];
        }
        if(!empty($p_num)){
            $where[] = ['o.p_num','=',$p_num];
        }
        if(!empty($type)){
            $where[] = ['o.type','=',$type];
        }
        else{
            $where[] = ['o.type','=',1];
        }
        if(!empty($startTime)){
            $where[] = ['o.addtime','>=',strtotime($startTime)];
        }
        if(!empty($endTime)){
            $where[] = ['o.addtime','<=',strtotime($endTime) + 86399];
        }
        if(!empty($paytime_min)){
            $where[] = ['o.paytime','>=',strtotime($paytime_min)];
        }
        if(!empty($paytime_max)){
            $where[] = ['o.paytime','<=',strtotime($paytime_max) + 86399];
        }
        if(is_numeric($state)){
            $where[] = ['o.state','=',$state];
        }
        $list = Order::orderList($where,1,99999);
        $info = [];
        if($type==1){
            foreach ($list as $item){
                $item['address'] = json_decode($item['address'],true);
                $item['addtime'] = date('Y-m-d H:i:s',$item['addtime']);
                if(!empty($item['paytime'])){
                    $item['paytime'] = date('Y-m-d H:i:s',$item['paytime']);
                }else{
                    $item['paytime'] = '';
                }
    //{"id":17,"uid":257,"phone":"13855467516","u_type":23,"province":"\u5b89\u5fbd\u7701","city":"\u6dee\u5357\u5e02","area":"\u51e4\u53f0\u53bf","address":"\u57ce\u5317\u6865\u6c7d\u8f66\u56db\u961f","street":"","enable":1,"addtime":"1713861822","default":1,"name":"\u66f9\u5148\u751f"}           
                //0代付款 1待发货 2待收货(待取货) 3已收货 4已评价 -1已取消 -2已退款
                if($item["state"]==0){
                    $item["status"] =  "待付款";
                }elseif($item["state"]==1){
                    $item["status"] =  "待发货";
                }elseif($item["state"]==2){
                    $item["status"] =  "待收货";
                }elseif($item["state"]==3){
                    $item["status"] =  "已收货";
                }elseif($item["state"]==4){
                    $item["status"] =  "已评价";
                }elseif($item["state"]==-1){
                    $item["status"] =  "已取消";
                }elseif($item["state"]==-2){
                    $item["status"] =  "已退款";
                }
    //            $item["status"] = ($item["state"]==1)?"待发货":"已发货";
                $item["address_name"] = $item["address"]["name"];
                $item["address_phone"] = $item["address"]["phone"];
                $item["address_info"] = $item["address"]["province"].$item["address"]["city"].$item["address"]["area"].$item["address"]["address"];
                
                if(isset($item["commission_info"]["sup_commission_price"])){
                    $item["sup_commission_price"]= $item["commission_info"]["sup_commission_price"];//团长
                }
                if(isset($item["commission_info"]["store_commission_price"])){
                    $item["store_commission_price"]= $item["commission_info"]["store_commission_price"];//门店
                }
                

                

                $info[] = $item;
            }
            $fileName = date('Y年m月d日H时i分',time());
            $Excel['fileName']=$fileName.'订单记录';//or $xlsTitle
            $Excel['cellName']=['A','B','C','D','E','F','G','H','I','J','K','M','N','L','O','P'];
            $Excel['H'] = ['A'=>28,'B'=>28,'C'=>28,'D'=>15,'E'=>28,'F'=>15,'G'=>28,'H'=>28,'I'=>60,'J'=>28,'K'=>28,'L'=>28,'M'=>28,'N'=>28,'O'=>28,'P'=>28];//横向水平宽度
            //$Excel['V'] = ['1'=>40,'2'=>26];//纵向垂直高度
            $Excel['sheetTitle']= date('Y年m月d日H时i分',time()).'导出订单记录';//大标题，自定义
            $Excel['xlsCell']=[
                ['phone','下单手机号'],
                ['username','下单用户'],
                ['p_name','商品名称'],
                ['order_quantity','下单量'],
                ['low_price','下单价'],
                ['status','状态'],
                ['address_name','收货人'],
                ['address_phone','收货人手机号'],
                ['address_info','收货人地址'],
                ['superor','团长名字'],//团长名字/团长手机号/团长分佣金额/门店名称/门店分佣金额
                ['superor_phone','团长手机号'],
                ['sup_commission_price','团长分佣金额'],
                ['s_name','门店名称'],
                ['store_commission_price','门店分佣金额'],
                ['addtime','添加时间'],
                ['paytime','下单时间'],

            ];
        }else{
            foreach ($list as $item){
                $item['address'] = json_decode($item['address'],true);
                $item['addtime'] = date('Y-m-d H:i:s',$item['addtime']);
                if(!empty($item['pay_time'])){
                    $item['pay_time'] = date('Y-m-d H:i:s',$item['pay_time']);
                }else{
                    $item['pay_time'] = '';
                }
    /*/*{"id":1,"province":"\u6d59\u6c5f\u7701","city":"\u676d\u5dde\u5e02","district":"\u897f\u6e56\u533a","address":"\u4e09\u58a9\u9f99\u6e56\u5929\u8857",
"store_name":"\u4e09\u58a9\u9f99\u6e56\u5929\u8857","business_hours_min":10,"business_hours_max":18,"reserved_1":null,
"enable":1,"addtime":"2024-03-02 13:30:30","selftime":"04-26 12:00-15:00"}              */
//0代付款 1待发货 2待收货(待取货) 3已收货 4已评价 -1已取消 -2已退款
                if($item["state"]==0){
                    $item["status"] =  "待付款";
                }elseif($item["state"]==1){
                    $item["status"] =  "待发货";
                }elseif($item["state"]==2){
                    $item["status"] =  "待收货";
                }elseif($item["state"]==3){
                    $item["status"] =  "已收货";
                }elseif($item["state"]==4){
                    $item["status"] =  "已评价";
                }elseif($item["state"]==-1){
                    $item["status"] =  "已取消";
                }elseif($item["state"]==-2){
                    $item["status"] =  "已退款";
                }
    //            $item["status"] = ($item["state"]==1)?"待发货":"已发货";
                $item["address_store_name"] = $item["address"]["store_name"];
                $item["address_phone"] = $item["phone"];
                $item["address_info"] = $item["address"]["province"].$item["address"]["city"].$item["address"]["district"].$item["address"]["address"];
                if(isset($item["commission_info"]["sup_commission_price"])){
                    $item["sup_commission_price"]= $item["commission_info"]["sup_commission_price"];//团长
                }
                if(isset($item["commission_info"]["store_commission_price"])){
                    $item["store_commission_price"]= $item["commission_info"]["store_commission_price"];//门店
                }
                $info[] = $item;
            }
            $fileName = date('Y年m月d日H时i分',time());
            $Excel['fileName']=$fileName.'订单记录';//or $xlsTitle
            $Excel['cellName']=['A','B','C','D','E','F','G','H','I','J','K','M','N','L','O','P'];
            $Excel['H'] = ['A'=>28,'B'=>28,'C'=>28,'D'=>15,'E'=>28,'F'=>15,'G'=>28,'H'=>28,'I'=>60,'J'=>28,'K'=>28,'L'=>28,'M'=>28,'N'=>28,'O'=>28,'P'=>28];//横向水平宽度
            //$Excel['V'] = ['1'=>40,'2'=>26];//纵向垂直高度
            $Excel['sheetTitle']= date('Y年m月d日H时i分',time()).'导出订单记录';//大标题，自定义
            $Excel['xlsCell']=[
                ['phone','下单手机号'],
                ['username','下单用户'],
                ['p_name','商品名称'],
                ['order_quantity','下单量'],
                ['low_price','下单价'],
                ['status','状态'],
                ['store_name','门店'],
//                ['address_phone','收货人手机号'],
//                ['address_info','收货人地址'],
                ['superor','团长名字'],//团长名字/团长手机号/团长分佣金额/门店名称/门店分佣金额
                ['superor_phone','团长手机号'],
                ['sup_commission_price','团长分佣金额'],
                ['s_name','门店名称'],
                ['store_commission_price','门店分佣金额'],
                ['addtime','添加时间'],
                ['pay_time','下单时间'],

            ];
        }
        self::excelPut($Excel,$info);
    }


    /**
     * Excel输出
     * @access public
     * @param  array     $Excel Excel相关配置信息
     * @param  array     $expTableData 表格里面的数据
     * @return file
     */
    public static function excelPut($Excel,$expTableData){
        //  ------------- 文件参数 -------------
        $cellName = $Excel['cellName'];
        $xlsCell = $Excel['xlsCell'];
        $cellNum = count($xlsCell);//计算总列数
        $dataNum = count($expTableData);//计算数据总行数
        $spreadsheet = new Spreadsheet();
        $sheet0 = $spreadsheet->getActiveSheet();
        $sheet0->setTitle("驿和邻里");
        //设置表格标题A1
        $sheet0->mergeCells('A1:'.$cellName[$cellNum-1].'1');//表头合并单元格

        // ------------- 表头 -------------
        $sheet0->setCellValue('A1',$Excel['sheetTitle']);

        $sheet0->getStyle('A1')->getFont()->setSize(20);
        $sheet0->getStyle('A1')->getFont()->setName('微软雅黑');
        //设置行高和列宽
        // ------------- 横向水平宽度 -------------
        if(isset($Excel['H'])){
            foreach ($Excel['H'] as $key => $value) {
                $sheet0->getColumnDimension($key)->setWidth($value);
            }
        }

        // ------------- 纵向垂直高度 -------------
        if(isset($Excel['V'])){
            foreach ($Excel['V'] as $key => $value) {
                $sheet0->getRowDimension($key)->setRowHeight($value);
            }
        }

        // ------------- 第二行：表头要加粗和居中，加入颜色 -------------
        $sheet0->getStyle('A1')->applyFromArray(['font' => ['bold' => false],'alignment' => ['horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,'vertical'=>PHPExcel_Style_Alignment::VERTICAL_CENTER]]);
        $setcolor = $sheet0->getStyle("A2:".$cellName[$cellNum-1]."2")->getFill();
        $setcolor->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $colors=['00a000','53a500','3385FF','00a0d0','0C8080','EFE4B0','8db4e2','00b0f0','0fb746','53a500','3385FF','00a0d0','0C8080','EFE4B0'];//设置总颜色
        $selectcolor=$colors[mt_rand(0,count($colors)-1)];//获取随机颜色
        $setcolor->getStartColor()->setRGB($selectcolor);

        // ------------- 根据表格数据设置列名称 -------------

        foreach ($xlsCell as $key => $value) {
            $sheet0->setCellValue($cellName[$key].'2', $value[1])
                ->getStyle($cellName[$key].'2')
                ->applyFromArray(['font' => ['bold' => true],'alignment' => ['horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,'vertical'=>PHPExcel_Style_Alignment::VERTICAL_CENTER]]);
        }

        // ------------- 渲染表中数据内容部分 -------------

        foreach ($expTableData as $keyi => $valuei) {
            foreach ($xlsCell as $keyj => $valuej) {
                $sheet0->getStyle($cellName[$keyj].($keyi+3))->applyFromArray(['alignment' => ['horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,'vertical'=>PHPExcel_Style_Alignment::VERTICAL_CENTER]]);
                $sheet0->setCellValueExplicit($cellName[$keyj] . ($keyi + 3), $valuei[$valuej[0]], PHPExcel_Cell_DataType::TYPE_STRING);
                $sheet0->getStyle($cellName[$keyj].($keyi+3))->getNumberFormat()->setFormatCode("@");

            }
        }
        // ------------- 设置边框 -------------
        $styleArray = [
            'borders' => [
                'allBorders' => [
                    'borderStyle' => Border::BORDER_THIN,
                    'color' => ['argb' => 'FF505050'],
                ],
            ],
        ];

        $sheet0->getStyle('A2:'.$cellName[$cellNum-1].($keyi+3))->applyFromArray($styleArray);

        // 冻结表格
        if(isset($Excel['freeze'])){
            $sheet0->freezePane($Excel['freeze']);
        }
        // ------------- 输出 -------------
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出07Excel文件
        //header('Content-Type:application/vnd.ms-excel');//告诉浏览器将要输出Excel03版本文件
        header("Content-Disposition: attachment;filename=".$Excel['fileName'].".xlsx");//告诉浏览器输出浏览器名称
        header('Cache-Control: max-age=0');//禁止缓存
        //$writer = new Xls($spreadsheet);//输出xls文件
        $writer = new Xlsx($spreadsheet);//输出xlsx文件
        $writer->save('php://output');
        exit;
    }

}
